package com.wjv.example.springboot.dubbo.consumer.service;

import org.apache.dubbo.common.utils.LRUCache;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.bootstrap.builders.ApplicationBuilder;
import org.apache.dubbo.config.bootstrap.builders.ReferenceBuilder;
import org.apache.dubbo.config.bootstrap.builders.RegistryBuilder;
import org.apache.dubbo.rpc.service.GenericService;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * <p>Title: GenericCallback</p>
 *
 * @author wjv
 * @date 2021/5/12 17:39
 */
@Component
public class GenericInvoker {

    private static Map<String, GenericService> genericServiceCache = new ConcurrentHashMap<>(20);

    public void doWork(String interfaceName) {
        // 当前应用配置
        ApplicationConfig application = ApplicationBuilder.newBuilder()
                .name("spbt-dubbo-consumer")
                .build();

        // 连接注册中心配置
        RegistryConfig registryConfig = RegistryBuilder.newBuilder()
                .address("nacos://localhost:8848")
                .simplified(true)
                .build();

        GenericService genericService = genericServiceCache.get(interfaceName);
        if (genericService == null) {
            // 引用远程服务
            // 该实例很重量，里面封装了所有与注册中心及服务提供方连接，请缓存
            ReferenceBuilder<GenericService> reference = new ReferenceBuilder<>();
            genericService = reference
                    .interfaceName(interfaceName)
                    .version("1.0.0")
                    .group("dev")
                    .generic(true) // 声明为泛化接口
                    .application(application)
                    .addRegistry(registryConfig)
                    .build()
                    .get(); // 用org.apache.dubbo.rpc.service.GenericService可以替代所有接口引用

            genericServiceCache.put(interfaceName, genericService);
        }

        // 基本类型以及Date,List,Map等不需要转换，直接调用
        Object result = genericService.$invoke("getTimeTags", new String[]{}, new Object[]{});

        System.out.println(result);
    }
}
